package com.atguigu.test;

import org.apache.flume.Context;
import org.apache.flume.Event;
import org.apache.flume.interceptor.Interceptor;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Map;

/**
 * 数据源过滤
 *
 * 给Event添加Header，用来区分字母和数字,再通过配置文件发到不同的channel
 * Builder.class-->build()-->initialize()-->intercept(List<Event> list)-->close()
 */
public class MyInterceptor implements Interceptor {

    public void initialize() {

    }

    /**
     * 处理一个Event,向Event的header中添加标志,以便于在配置文件中将不同的Event发送到不同的sink
     * @param event
     * @return
     */

    public Event intercept(Event event) {
        //收到的Event有三种情况
        byte[] body = event.getBody();
        Map<String, String> headers = event.getHeaders();
        //将body编码成String
        String line = null;
        try {
            line = new String(body,"UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        //获取第一个字符
        char c = line.charAt(0);
        if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {
            //首字符为字母
            headers.put("type", "zm");
        } else if (c >= '0' && c <= '9') {
            //首字符为数字
            headers.put("type", "sz");
        } else {
            //其他情况，抛弃不要
            return null;
        }
        return event;
    }

    public List<Event> intercept(List<Event> list) {
        for (Event event : list) {
            intercept(event);
        }
        return list;
    }

    public void close() {

    }

    public static class Builder implements Interceptor.Builder {
        public Interceptor build() {
            return new MyInterceptor();
        }
        /**
         * 配置方法，可以从配置文件中配置我们的Interceptor
         * @param context 配置文件
         */
        public void configure(Context context) {

        }
    }

}
